<template>
  <div class="task-con">
    <div class="top-tab">
      <a-tabs v-model:active-key="curPage" @change="tabChange" size="mini">
        <a-tab-pane v-for="item in tabList" :key="item.key">
          <template #title>
            <span>{{ item.label }}</span>
            <span>({{ item.num ? item.num : '0' }})</span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div v-if="curPage != '抢单'" class="table-bottom table-gl-w">
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :max-num="4" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getList" fromLocation="团队任务导出" :checkedList="ids" :seachData="{ ...searchValue, status: curPage }" :showExport="true" :exportInfo="exportInfo">
          <template #headerLeft>
            <a-space>
              <!-- <div style="margin: 5px 0 5px 10px">合计任务：{{ statictsInfo.sumNum }}条 合计任务费用：￥{{ transNumberToShort(statictsInfo.amtSumAmount, 4) }} </div> -->
              <a-radio-group v-if="curPage == 'SENDING_SAMPLE'" type="button" v-model="sampleStatus" @change="getList">
                <a-radio value="WAIT_SEND_SAMPLE">待送样</a-radio>
                <a-radio value="WAIT_RECEIVE_SAMPLE">待收样</a-radio>
              </a-radio-group>
              <a-button v-if="curPage == 'SENDING_SAMPLE'" class="gray-outline" @click="showConfirmReceiptSample('mul')">确认收到样品</a-button>
              <a-button v-if="['SENDING_SAMPLE', 'WAIT_SCHEDULE'].includes(curPage)" class="gray-outline" @click="setExecuteUSer">设置任务执行人</a-button>
              <a-button v-if="['EXECUTING'].includes(curPage)" class="gray-outline" @click="setExecuteUSer">修改任务执行人</a-button>
              <a-button v-if="['SENDING_SAMPLE', 'WAIT_SCHEDULE'].includes(curPage)" class="gray-outline" @click="cancelTakeOrder">取消接单</a-button>
              <a-button v-if="['WAIT_ACCEPT'].includes(curPage)" class="gray-outline" @click="isTakeOrder('reject')">拒绝接单</a-button>
              <a-button v-if="['WAIT_ACCEPT'].includes(curPage)" class="gray-outline" @click="isTakeOrder('agree')">同意接单</a-button>
              <a-button v-if="['EXECUTING', 'WAIT_SCHEDULE'].includes(curPage)" @click="submitAccept" class="gray-outline">提交验收</a-button>
              <a-button v-if="['WAIT_CHECK'].includes(curPage)" @click="waitCheck" class="gray-outline">审核</a-button>
              <a-button @click="setTag('mul')" class="gray-outline">设置标签</a-button>
              <a-checkbox v-if="['WAIT_SCHEDULE'].includes(curPage)" @change="sizeChange(pageNation.pageSize)" v-model="noExecuter">仅显示未设置执行人</a-checkbox>
              <!-- <a-button v-if="['WAIT_ACCEPT'].includes(curPage)" type="text" @click="router.push('/designSupplier/task/grabOrder')">去任务池抢单</a-button> -->
            </a-space>
          </template>
          <template #headerRight>
            <sortKey :list="sortKeyList" @save="getListBySortKey" />
          </template>
          <template #tableBody>
            <a-table size="mini" :bordered="{ headerCell: true }" v-model:selected-keys="ids" row-key="id" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-two-line" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column title="序号" #cell="{ rowIndex }" :width="50" fixed="left">{{ rowIndex + 1 }}</a-table-column>
                <a-table-column title="图片" #cell="{ record }" :width="60" fixed="left">
                  <ImgPopover :src="imgUrl(record)">
                    <template #con>
                      <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                    </template>
                  </ImgPopover>
                </a-table-column>
                <a-table-column title="SKU" #cell="{ record }" :width="150" fixed="left" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="product.sku">
                  <a-popover v-if="$extract(record, 'product.sku')">
                    <div @click="showSkuDetail(record)" class="highlight cursor text-limit">{{ $extract(record, 'product.sku') || '--' }}</div>
                    <template #content>
                      <div style="max-width: 300px">
                        {{ $extract(record, 'product.sku') || '--' }}
                      </div>
                    </template>
                  </a-popover>
                  <!-- <TextLimit class="highlight cursor" position="top" :rows="1" :val="$extract(record, 'product.sku') || '--'" /> -->
                  <div v-else>--</div>
                </a-table-column>
                <a-table-column title="采购下单" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="product.gmtPurchase"> {{ $setTime($extract(record, 'product.gmtPurchase'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="采购入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="product.gmtPurchaseWarehouse"> {{ $setTime($extract(record, 'product.gmtPurchaseWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="货件发货" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="product.gmtShipmentShipped"> {{ $setTime($extract(record, 'product.gmtShipmentShipped'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="货件入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="product.gmtShippmentWarehouse"> {{ $setTime($extract(record, 'product.gmtShippmentWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>

                <!-- <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column> -->
                <a-table-column title="服务内容" #cell="{ record }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="taskRequire.serContent">
                  <!-- <TextLimit :val="$extract(record, 'taskRequire.serContent')" :rows="1" position="top" /> -->
                  <a-popover>
                    <div class="text-limit">{{ $extract(record, 'taskRequire.serContent') }}</div>
                    <template #content>
                      <div style="max-width: 300px">
                        {{ $extract(record, 'taskRequire.serContent') }}
                      </div>
                    </template>
                  </a-popover>
                </a-table-column>
                <a-table-column v-if="$authPass('task.ser.read.amount')" title="任务费用" #cell="{ record }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="amtbCost">
                  <div style="color: red">￥{{ $extract(record, 'amtbCost') }}</div>
                </a-table-column>

                <a-table-column title="甲方" #cell="{ record }" :width="100"> {{ $extract(record, 'deductionInfo.consumerAccountUserName') }} </a-table-column>
                <a-table-column title="雇主" #cell="{ record }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="employer.name">
                  <div>{{ $extract(record, 'employer.name') || '--' }}</div>
                  <div class="common-text">{{ $extract(record, 'employer.deptName') || '--' }}</div>
                </a-table-column>
                <a-table-column title="类型/ID" #cell="{ record }" :width="160">
                  <div>{{ typeMap[record.type] }}</div>
                  <a-space>
                    <div class="highlight cursor" @click="viewDetial(record)">{{ record.code }}</div>
                    <div v-if="$extract(record.taskRequire, 'isSample')">
                      <span style="color: #979797" class="icon icon-yangpin"></span>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="任务执行人" #cell="{ record }" :width="100">
                  <div class="task_user" style="width: 100%; height: 100%">
                    <a-space>
                      <a-popover>
                        <div class="text-limit" style="width: 80px">{{ getExecuterUser(record) || '--' }}</div>
                        <template #content>
                          <div style="max-width: 300px">
                            {{ getExecuterUser(record) || '--' }}
                          </div>
                        </template>
                      </a-popover>

                      <!-- <TextLimit :val="getExecuterUser(record) || '--'" /> -->
                      <icon-edit v-if="['WAIT_ACCEPT', 'SENDING_SAMPLE', 'WAIT_SCHEDULE', 'EXECUTING'].includes(record.status)" class="task_user-icon highlight ml10 cursor" @click="editUser(record)" />
                    </a-space>
                  </div>
                </a-table-column>
                <a-table-column title="预计交付日期" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtPlanDelivery">
                  <div>{{ $setTime(record.gmtPlanDelivery, 'YYYY-MM-DD') }}</div>
                  <div v-if="record.gmtPlanDelivery">
                    <div style="color: red" v-if="!toCheckDay(record.gmtPlanDelivery).type">超时{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                    <div class="highlight" v-else>剩余{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                  </div>
                </a-table-column>

                <a-table-column title="发布时间" v-if="['WAIT_ACCEPT'].includes(curPage)" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtPublish">
                  {{ $setTime(record.gmtPublish, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>

                <a-table-column v-if="['SENDING_SAMPLE', 'WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="接单时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtTake">
                  {{ $setTime(record.gmtTake, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="到样时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtSampleDelivery">
                  {{ $setTime(record.gmtSampleDelivery, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="排期时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtSchedule">
                  {{ $setTime(record.gmtSchedule, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['WAIT_VERIFY'].includes(curPage)" title="提交时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtSubmitVerify">
                  {{ $setTime(record.gmtSubmitVerify, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="curPage != 'SENDING_SAMPLE'" title="完成时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtFinish">
                  {{ $setTime(record.gmtFinish, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="curPage == ''" title="状态" #cell="{ record }" :width="130">
                  {{ tabKeyMap[record.status] }}
                </a-table-column>

                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样地址" #cell="{ record }" :width="130">
                  {{ $extract(record, 'sendSample.sampleAddress.stateOrRegion') }}
                  {{ $extract(record, 'sendSample.sampleAddress.city') }}
                  {{ $extract(record, 'sendSample.sampleAddress.address') }}
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样方式" #cell="{ record }" :width="130">
                  <a-space>
                    <div>{{ record.sendType == 'DOOR_DELIVERY' ? '快递' : '送货上门' }}</div>
                    <!-- <div> <icon-edit /> </div> -->
                  </a-space>
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送出日期" :sortable="{ sortDirections: ['ascend', 'descend'], sorter: true }" data-index="gmtSend" #cell="{ record }" :width="130">
                  {{ $setTime($extract(record, 'sendSample.gmtSend'), 'YYYY/MM/DD') }}
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="物流商/跟踪号" #cell="{ record }" :width="130">
                  <div>{{ $extract(record, 'sendSample.logistics') ? $extract(record, 'sendSample.logistics') : '--' }}</div>
                  <div>{{ $extract(record, 'sendSample.trackingNumber') ? $extract(record, 'sendSample.trackingNumber') : '--' }}</div>
                </a-table-column>

                <a-table-column title="标签" #cell="{ record }" :width="140">
                  <div>
                    <a-space wrap>
                      <a-tag size="small" v-for="tag in record.tagList" :key="tag.id" :color="tag.color">{{ tag.name }}</a-tag>
                      <div class="cursor" @click="setTag('single', record)"><icon-edit /></div>
                    </a-space>
                  </div>
                </a-table-column>

                <a-table-column title="留言" #cell="{ record }" :width="80">
                  <a-space>
                    <div>{{ getNum(record.leaveMsgList) }}</div>
                    <div>
                      <div v-if="record.hasPartaNewLeaveMsg == null || record.hasPartaNewLeaveMsg == false">
                        <icon-message @click="showMsgModal(record)" class="cursor" :style="{ fontSize: '18px' }" />
                      </div>
                      <div v-else>
                        <a-badge :count="1" dot :offset="[2, -2]">
                          <icon-message @click="showMsgModal(record)" class="cursor" :style="{ color: '#f59a23', fontSize: '18px', verticalAlign: '-3px' }" />
                        </a-badge>
                      </div>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="操作" #cell="{ record }" :width="110" fixed="right">
                  <a-button v-if="record.status" type="text" @click="viewDetial(record)">详情</a-button>
                  <a-button class="ml10" v-if="record.status == 'NEGOTIATE_TERMINATED'" type="text" @click="negotiate(record)">协商</a-button>
                  <a-button class="ml10" v-if="curPage == 'SENDING_SAMPLE'" type="text" @click="showConfirmReceiptSample('single', record)">确认收样</a-button>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
    <div v-else>
      <gradOrder @inGrabOrder="searchValue = {}" />
    </div>
  </div>

  <msglist v-if="showMsgListModal" v-model="showMsgListModal" :info="taskDetailInfo" @save="save" />
  <!-- 拒绝接单 -->
  <rejectTakeTask v-if="showRejectTakeTaskModal" v-model="showRejectTakeTaskModal" :ids="ids" @save="save" />
  <!-- 同意接单 -->
  <takeTask v-if="showTakeTaskModal" :taskType="takeOrderTaskType" :isEditUser="isEditUser" :list="selItemsList" v-model="showTakeTaskModal" :ids="ids" @save="save" />
  <!-- 设置任务执行人 -->
  <setTaskExecuteUser v-if="showExecuteUserModal" :taskType="takeOrderTaskType" :list="selItemsList" v-model="showExecuteUserModal" :ids="ids" @save="save" />
  <!-- 确认收样 -->
  <confirmReceiptSample v-if="showConfirmReceiptSampleModal" v-model="showConfirmReceiptSampleModal" :ids="ids" @save="save" />
  <!-- 详情 -->
  <viewTaskDetail v-if="showViewTaskDetailModal" v-model="showViewTaskDetailModal" isTeamtype="isTeam" :info="taskDetailInfo" @save="save" />
  <!-- 协商任务 -->
  <negotiateTask v-if="showNegotiateTaskModal" v-model="showNegotiateTaskModal" :info="taskDetailInfo" @save="save" />
  <!-- 标签 -->
  <tag ref="Tag" :dataList="editShowTagList" :idList="ids" @save="tagSave" />
  <!-- sku详情 -->
  <skuDetail ref="SKU" :info="taskDetailInfo" />
  <!-- 审核 -->
  <waitCheckModal v-if="showWaitCheckModal" v-model="showWaitCheckModal" :ids="ids" @save="save" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { findTeamTaskPage, listByParam, countTeamTaskStatus, statTaskFromLocation, cancelTakeTask, findNoTakeTaskCount, submitVerifyTask } from '@/api/task'
  import { transNumberToShort } from '@/utils'
  import { Message, Modal } from '@arco-design/web-vue'
  import { useRouter } from 'vue-router'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import msglist from './components/msgList.vue'
  import rejectTakeTask from './components/rejectTakeTask.vue'
  import takeTask from './components/takeTask.vue'
  import setTaskExecuteUser from './components/setTaskExecuteUser.vue'
  import confirmReceiptSample from './components/confirmReceiptSample.vue'
  import viewTaskDetail from './components/viewDetail/viewdetailIndex.vue'
  import negotiateTask from './components/negotiateTask.vue'
  import tag from './components/tag/tagList.vue'
  import skuDetail from './components/skuDetail.vue'
  import gradOrder from './grabOrder.vue'
  import waitCheckModal from './components/waitCheckModal.vue'
  import sortKey from './components/sortKey.vue'
  import _ from 'lodash-es'
  const router = useRouter()

  const sortKeyList = [
    { name: 'SKU', key: 'product.sku' },
    { name: '采购下单', key: 'product.gmtPurchase' },
    { name: '采购入库', key: 'product.gmtPurchaseWarehouse' },
    { name: '货件发货', key: 'product.gmtShipmentShipped' },
    { name: '货件入库', key: 'product.gmtShippmentWarehouse' },
    { name: '服务内容', key: 'taskRequire.serContent' },
    { name: '任务费用', key: 'amtbCost' },
    { name: '雇主', key: 'employer.name' },
    { name: '预计交付日期', key: 'gmtPlanDelivery' },
    { name: '发布时间', key: 'gmtPublish' },
    { name: '完成时间', key: 'gmtFinish' },
  ]

  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }

  const tabKeyMap = {
    WAIT_PUBLISH: '待发布',
    WAIT_ACCEPT: '待接单',
    SENDING_SAMPLE: '送样中',
    WAIT_SCHEDULE: '待执行',
    EXECUTING: '执行中',
    WAIT_VERIFY: '待验收',
    FINISHED: '已完成',
    NEGOTIATE_TERMINATED: '协商终止',
    TERMINATED: '已终止',
  }

  const Tag = ref()
  const SKU = ref()

  let curPage = ref('WAIT_ACCEPT')
  let tabList = ref([
    { label: '抢单', num: '', key: '抢单' },
    { label: '待接单', num: '', key: 'WAIT_ACCEPT' },
    { label: '送样中', num: '', key: 'SENDING_SAMPLE' },
    { label: '待执行', num: '', key: 'WAIT_SCHEDULE' },
    { label: '执行中', num: '', key: 'EXECUTING' },
    { label: '待审核', num: '', key: 'WAIT_CHECK' },
    { label: '待验收', num: '', key: 'WAIT_VERIFY' },
    { label: '协商终止', num: '', key: 'NEGOTIATE_TERMINATED' },
    { label: '已完成', num: '', key: 'FINISHED' },
    { label: '全部任务', num: '', key: '' },
    // { label: '待认领', num: '', key: '' },
  ])
  let statictsInfo: any = ref({})
  let searchValue: any = ref({})
  let tableList = ref()
  let loading = ref(false)
  let noExecuter = ref(false)
  let ids = ref<Array<string>>([])
  let taskType: any = ref('')
  let sampleStatus: any = ref('')
  let takeOrderTaskType: any = ref('')
  let taskDetailInfo: any = ref({})
  let showTaskDetailModal = ref(false)
  let showRejectTakeTaskModal = ref(false)
  let showTakeTaskModal = ref(false)
  let showMsgListModal = ref(false)
  let showExecuteUserModal = ref(false)
  let showConfirmReceiptSampleModal = ref(false)
  let showViewTaskDetailModal = ref(false)
  let showNegotiateTaskModal = ref(false)
  let showWaitCheckModal = ref(false)
  let selItemsList: any = ref([])
  let isEditUser: any = ref('add')
  let editShowTagList: any = ref([])
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  const filterItem: any = ref([
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 260,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'serContentList',
      keyItems: [
        { label: '任务ID', value: 'codeList' },
        { label: '服务内容', value: 'serContentList' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '服务内容',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'companyName',
      keyItems: [
        { label: '甲方', value: 'companyName' },
        { label: '雇主', value: 'employerName' },
        { label: '任务执行人', value: 'executerName' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '甲方',
      width: 180,
    },

    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报设计', value: 'POSTER_SHOP_DESIGN' },
        { label: '换钻调色', value: 'CHANGE_DIAMOND_COLOR' },
        { label: '手绘设计', value: 'HAND_DRAWN_DESIGN' },
      ],
    },

    {
      key: 'tagCodeList',
      label: '任务标签',
      value: ref(),
      type: 'select_multiple',
      width: '100%',
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },

    {
      type: 'keyword_date_range_custom',
      key: 'gmtPlanDelivery',
      keyItems: [{ label: '预计交付日期', value: 'gmtPlanDelivery' }],
      keyWidth: '110',
      label: '预计交付日期',
      value: ref(),
      width: 200,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtPublish',
      keyItems: [
        { label: '发布时间', value: 'gmtPublish' },
        { label: '接单时间', value: 'gmtTake' },
        { label: '到样时间', value: 'gmtSampleDelivery' },
        { label: '排期时间', value: 'gmtSchedule' },
        { label: '提交时间', value: 'gmtSubmitVerify' },
      ],
      keyWidth: '110',
      label: '发布时间',
      value: ref(),
      width: 200,
    },
    {
      type: 'keyword_date_range_custom',
      key: 'product.gmtPurchase',
      keyItems: [
        { label: '采购下单时间', value: 'product.gmtPurchase' },
        { label: '采购入库时间', value: 'product.gmtPurchaseWarehouse' },
        { label: '货件发货时间', value: 'product.gmtShipmentShipped' },
        { label: '货件入库时间', value: 'product.gmtShippmentWarehouse' },
      ],
      keyWidth: '110',
      label: '采购下单时间',
      value: ref(),
      width: 200,
    },
    // {
    //   key: 'priority',
    //   label: '优先级',
    //   value: ref(),
    //   type: 'select',
    //   width: '100%',
    //   optionItems: [
    //     { label: '急', value: 'URGENT' },
    //     { label: '高', value: 'HIGH' },
    //     { label: '中', value: 'MIDDLE' },
    //     { label: '低', value: 'LOW' },
    //   ],
    //   attrs: {
    //     'allow-clear': true,
    //   },
    // },
  ])

  let exportInfo: any = ref({
    title: '导出团队任务',
    type: 'single',
    supportAll: true,
    tabName: '导出团队任务',
    fieldList: [
      {
        group: '基础信息',
        columns: [
          {
            name: '序号',
            key: 'sort',
            keyType: '1',
          },
          {
            key: 'product.productPicList',
            name: '图片',
            keyType: '2',
          },
          {
            key: 'product.sku',
            name: 'SKU',
            keyType: '1',
          },
          {
            key: 'status',
            name: '状态',
            keyType: '1',
          },
          {
            key: 'product.gmtPurchase',
            name: '采购下单',
            keyType: '1',
          },
          {
            key: 'product.gmtPurchaseWarehouse',
            name: '采购入库',
            keyType: '2',
          },
          {
            key: 'product.gmtShipmentShipped',
            name: '货件发货',
            keyType: '1',
          },
          {
            key: 'product.gmtShippmentWarehouse',
            name: '货件入库',
            keyType: '1',
          },
          {
            key: 'taskRequire.serContent',
            name: '服务内容',
            keyType: '1',
          },
          {
            key: 'amtbCost',
            name: '任务费用',
            keyType: '1',
          },
          {
            key: 'companyShortName',
            name: '甲方',
            keyType: '1',
          },
          {
            key: 'employer.name',
            name: '雇主',
            keyType: '1',
          },
          {
            key: 'type',
            name: '类型',
            keyType: '1',
          },
          {
            key: 'code',
            name: 'ID',
            keyType: '1',
          },
          {
            key: 'executerList',
            name: '任务执行人',
            keyType: '1',
          },
          {
            key: 'gmtPlanDelivery',
            name: '预计交付时间',
            keyType: '1',
          },
          {
            key: 'gmtTake',
            name: '接单时间',
            keyType: '1',
          },
          {
            key: 'gmtSampleDelivery',
            name: '到样时间',
            keyType: '1',
          },
          {
            key: 'gmtSchedule',
            name: '排期时间',
            keyType: '1',
          },
          {
            key: 'gmtSubmitVerify',
            name: '提交时间',
            keyType: '1',
          },
          {
            key: 'gmtPublish',
            name: '发布时间',
            keyType: '1',
          },
          {
            key: 'gmtFinish',
            name: '完成时间',
            keyType: '1',
          },
          {
            key: 'tagList',
            name: '标签',
            keyType: '1',
          },
        ],
      },
    ],
    supportTemplate: true,
    templateType: 'TEAM_TASK_UPLOAD',
    exportApi: 'exportTeamTask',
    excelName: '团队任务导出',
  })

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)

    if (searchValue.value.startDate) {
      searchValue.value.startDate = new Date(`${searchValue.value.startDate} 00:00:00`).valueOf()
      searchValue.value.endDate = new Date(`${searchValue.value.endDate} 23:59:59`).valueOf()
    }
    if (searchValue.value.codeList) {
      searchValue.value.codeList = searchValue.value.codeList.split(',')
    }

    // if (searchValue.value.gmtPurchase123) {
    //   searchValue.value.gmtExpectDeliveryStart = new Date(`${searchValue.value.gmtPurchase123.split(',')[0]} 00:00:00`).valueOf()
    //   searchValue.value.gmtExpectDeliveryEnd = new Date(`${searchValue.value.gmtPurchase123.split(',')[1]} 23:59:59`).valueOf()
    // } else {
    //   delete searchValue.value.gmtExpectDeliveryStart
    //   delete searchValue.value.gmtExpectDeliveryEnd
    // }
    getList()
  }
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    tableList.value = []
    getList()
  }

  const getList = async () => {
    let params = {
      ...searchValue.value,
      status: curPage.value,
      // noExecuter: noExecuter.value,
      // taskType: taskType.value,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    if (params.status == 'SENDING_SAMPLE') {
      params.sampleStatus = sampleStatus.value
    }

    if (params.status == 'WAIT_SCHEDULE') {
      params.noExecuter = noExecuter.value
    }
    loading.value = true
    const res: any = await findTeamTaskPage(params)
    if (res) {
      tableList.value = res?.data?.records
      console.log(tableList.value, 'tableList.value')
      pageNation.value.total = res?.data?.total
    }
    getStatusNum()
    ids.value = []
    loading.value = false
  }

  const toCheckDay = (time: any) => {
    let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
    let newDate = new Date().valueOf()
    let timeStr = 0
    if (date > newDate) {
      timeStr = date - newDate
    } else {
      timeStr = newDate - date
    }
    const formatTimeFromTimestamp = (timestamp: number) => {
      let text = ''
      const days = Math.floor(timestamp / (60 * 60 * 24 * 1000))
      const hours = Math.floor((timestamp % (60 * 60 * 24 * 1000)) / (60 * 60 * 1000))
      text = days > 0 ? `${days}天${hours}小时` : `${Math.abs(hours)}小时`
      return text
    }
    if (date - newDate < 0) {
      return {
        type: false,
        day: formatTimeFromTimestamp(timeStr),
      }
    } else {
      return {
        type: true,
        day: formatTimeFromTimestamp(timeStr),
      }
    }
  }

  const filterStatus = (val: string) => {
    let item = tabList.value.find((item: any) => {
      return item.key == val
    })
    return item?.label || '未知状态'
  }

  const getNum = (list: any) => {
    if (list && list instanceof Array) {
      return list.length > 99 ? '99+' : list.length
    } else {
      return '0'
    }
  }

  const showModal = (type: string, info?: any) => {
    taskType.value = type
    taskDetailInfo.value = info
    showTaskDetailModal.value = true
  }

  const viewDetial = (info: any) => {
    taskDetailInfo.value = info
    showViewTaskDetailModal.value = true
  }

  const tabChange = () => {
    pageNation.value.pageNum = 1
    getList()
  }

  const showMsgModal = (info: any) => {
    taskDetailInfo.value = info
    showMsgListModal.value = true
  }
  const negotiate = (info: any) => {
    taskDetailInfo.value = info
    showNegotiateTaskModal.value = true
  }

  const getStatusNum = async () => {
    const res: any = await countTeamTaskStatus({})
    // tabList.value[0].num = res.data?.allNum
    tabList.value[1].num = res.data?.waitAcceptNum
    tabList.value[2].num = res.data?.sendingSampleNum
    tabList.value[3].num = res.data?.waitScheduleNum
    tabList.value[4].num = res.data?.executingNum
    tabList.value[5].num = res.data?.waitCheckNum
    tabList.value[6].num = res.data?.waiteVerifyNum
    tabList.value[7].num = res.data?.negotiateTerminatedNum
    tabList.value[8].num = res.data?.finishedNum
    tabList.value[9].num = res.data?.allNum
  }

  const isTakeOrder = (type: string) => {
    if (!ids.value[0]) return Message.error('请选择要操作的任务')
    // let typeArr: Array<string> = []
    // ids.value.forEach((e: any) => {
    //   let item: any = tableList.value.find((item: any) => {
    //     return item.id == e
    //   })
    //   if (item && typeArr.indexOf(item.type) == -1) typeArr.push(item.type)
    // })
    // if (typeArr.length > 1) return Message.error('每次只能接相同类型的任务')
    // takeOrderTaskType.value = typeArr[0]
    selItemsList.value = []
    selItemsList.value = tableList.value.filter((item: any) => {
      return ids.value.indexOf(item.id) > -1
    })
    type == 'reject' ? (showRejectTakeTaskModal.value = true) : ((showTakeTaskModal.value = true), (isEditUser.value = 'add'))
  }

  const setExecuteUSer = () => {
    if (!ids.value[0]) return Message.error('请选择要操作的任务')
    // let typeArr: Array<string> = []
    // ids.value.forEach((e: any) => {
    //   let item: any = tableList.value.find((item: any) => {
    //     return item.id == e
    //   })
    //   if (item && typeArr.indexOf(item.type) == -1) typeArr.push(item.type)
    // })
    // if (typeArr.length > 1) return Message.error('每次只能接相同类型的任务')
    // takeOrderTaskType.value = typeArr[0]
    selItemsList.value = []
    selItemsList.value = tableList.value.filter((item: any) => {
      return ids.value.indexOf(item.id) > -1
    })
    showExecuteUserModal.value = true
  }

  const getExecuterUser = (arr: any) => {
    let newArr = arr?.executerList || []
    return newArr.map((item: any) => item.name).join(',')
  }

  const showConfirmReceiptSample = (type: string, info?: any) => {
    if (type == 'mul' && !ids.value[0]) return Message.error('请选择要操作的任务')
    if (type == 'single') ids.value.push(info.id)
    showConfirmReceiptSampleModal.value = true
  }

  const imgUrl = (data: any) => {
    let arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  const save = () => {
    ids.value = []
    getList()
  }

  const getStaticsInfo = async () => {
    let params = {
      ...searchValue.value,
      statLocation: 'Y_TEAM_TASK',
    }
    const res: any = await statTaskFromLocation(params)
    if (res) {
      statictsInfo.value = res?.data || {}
    }
  }

  const editUser = (info: any) => {
    selItemsList.value = []
    selItemsList.value.push(info)
    isEditUser.value = 'edit'
    if (['WAIT_ACCEPT'].includes(info.status)) {
      showTakeTaskModal.value = true
    } else if (['SENDING_SAMPLE', 'WAIT_SCHEDULE', 'EXECUTING'].includes(info.status)) {
      showExecuteUserModal.value = true
    }
  }

  const cancelTakeOrder = async () => {
    if (!ids.value[0]) return Message.error('请选择要操作的任务')
    Modal.error({
      title: '取消接单',
      content: '请再次确认是否要取消接单',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let params = {
          idList: ids.value,
        }
        const res: any = await cancelTakeTask(params)
        if (res) {
          Message.success('取消接单成功')
          ids.value = []
          getList()
        }
      },
    })
  }

  const setTag = (type: string, info?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要设置标签的任务')
    }
    if (type != 'mul') ids.value.push(info.id)
    editShowTagList.value = []
    tableList.value.forEach((item: any) => {
      if (ids.value.indexOf(item.id) > -1) {
        if (item.tagList) editShowTagList.value = [...editShowTagList.value, ...item.tagList]
      }
    })

    console.log(editShowTagList.value)

    Tag.value.visible = true
  }

  const tagSave = () => {
    ids.value = []
    setTimeout(() => {
      getList()
    }, 1000)
  }

  const getTagList = async () => {
    const res: any = await listByParam({ source: 'TASK' })
    let arr = res.data || []
    arr.map((e: any) => {
      e.label = e.name
      e.value = e.code
      return e
    })
    filterItem.value[4].optionItems = arr
  }

  const showSkuDetail = (info: any) => {
    taskDetailInfo.value = info
    SKU.value.visible = true
  }

  const getNoTakeTaskCount = async () => {
    const res: any = await findNoTakeTaskCount({})
    tabList.value[0].num = res.data || 0
  }

  const submitAccept = () => {
    if (!ids.value[0]) {
      return Message.error('请选择要提交的任务')
    }
    Modal.info({
      title: '提示',
      content: '是否要批量提交任务',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let params = {
          idList: ids.value,
          teamSumbitVerify: true,
        }
        const res: any = await submitVerifyTask(params)
        if (res) {
          Message.success('提交验收成功')
          ids.value = []
          getList()
        }
      },
    })
  }

  const waitCheck = () => {
    // if (!ids.value[0]) {
    //   return Message.error('请选择要审核的任务')
    // }
    showWaitCheckModal.value = true
  }

  const getListBySortKey = (list: any) => {
    searchValue.value.customSortList = list
    if (list[0]) getList()
  }

  onMounted(() => {
    getList()
    getStaticsInfo()
    getTagList()
    getNoTakeTaskCount()
  })
</script>

<style lang="less" scoped>
  .task_user {
    min-width: 60px;
    min-height: 20px;
    &:hover {
      .task_user-icon {
        font-size: 14px;
        display: inline-block;
      }
    }
    .task_user-icon {
      display: none;
    }
  }

  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }

  .task-con {
    height: 100%;
    .top-tab {
      background-color: white;
    }
    .table-bottom {
      height: calc(100vh - @menuAndTabHeight);
    }
  }

  .level-btn {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 12px;
  }

  .level-1 {
    background-color: #ffff80;
    color: black;
  }
  .level-2 {
    background-color: #a30014;
    color: white;
  }
  .level-3 {
    background-color: #d9001b;
    color: white;
  }
  .level-4 {
    background-color: #ec808d;
    color: white;
  }
</style>
